package com.yfm.codec;

import com.yfm.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> genericClass;

    public RpcDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
       System.out.println("decode....");
        if (in.readableBytes() < 4) {
            return;
       }
        System.out.println("decode....");
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            System.out.println("return"+in.readableBytes()+"decode...."+dataLength);
            in.resetReaderIndex();
            return;
        }
        System.out.println("decode...."+dataLength);
        byte[] data = new byte[dataLength];
         in.readBytes(data);
        System.out.println(SerializationUtil.deserialize(data, genericClass));
        out.add(SerializationUtil.deserialize(data, genericClass));
    }
}
